当我们对运行时资源进行缓存操作时,并没有一个统一标准来指明该资源是有效且可以被缓存的,在 Workbox 中,我们可以使用
workbox-cacheable-response模块,根据Response Status Code或Response Headers来决定是否对资源进行缓存操作。基于此,本章我们将讨论workbox-cacheable-response模块的使用。
# 基本使用
workbox.routing.registerRoute(
new RegExp('^https://third-party\\.example\\.com/images/'),
new workbox.strategies.CacheFirst({
cacheName: 'image-cache',
plugins: [
new workbox.cacheableResponse.Plugin({
statuses: [0, 200],
headers: {
'Is-Cacheable': 'true',
'X-Is-Cacheable': 'true'
}
})
]
})
);
@前端进阶之旅: 代码已经复制到剪贴板
上例中,我们通过在
workbox.strategies.CacheFirst的plugins属性中添加workbox.cacheableResponse.Plugin实例来设置指定路由可被缓存的条件,该路由的响应将在 Response Status Code 为 0 或 200,并且Response Headers中包含Is-Cacheable=true或X-Is-Cacheable=true时进行缓存处理。另外,亦可单独指定 statuses 或headers属性以达到只根据Response Status Code或Response Headers来判断资源是否可被缓存的目的。
workbox.cacheableResponse.Plugin的使用非常简单,由于它只能在workbox.strategies模块的CacheFirst、NetworkFirst及StaleWhileRevalidate中使用,因此我们可直接使用workbox.cacheableResponse.CacheableResponse在自定义的请求策略中完成资源是否可缓存的逻辑处理,比如:
const cacheable = new workbox.cacheableResponse.CacheableResponse({
statuses: [0, 200],
headers: {
'Is-Cacheable': 'true',
'X-Is-Cacheable': 'true'
}
});
const response = await fetch('/path/to/api');
if (cacheable.isResponseCacheable(response)) {
const cache = await caches.open('api-cache');
cache.put(response.url, response);
} else {
}
@前端进阶之旅: 代码已经复制到剪贴板
# 默认处理
在
workbox.strategies模块的
